# -*- coding: utf-8 -*
import pandas
import getopt, sys

class CsvToHtml():
    def __init__(self, inFile, outFile, title):
        self.inFile = inFile
        self.outFile = outFile
        self.title = title

    def createReport(self):
        data = pandas.read_csv(self.inFile, dtype=object)
        df = pandas.DataFrame(data)
        pagesList = []

        for i in range(len(df)):
            row = df[i:i+1]
            name = row['Name'][i]
            samples = row['Request Count'][i]
            failures = row ['Failure Count'][i]
            avgtime = int(float(row['Average Response Time'][i])+0.5)
            mintime = row['Min Response Time'][i]
            maxtime = row['Max Response Time'][i]
            tps = format(float(row['Requests/s'][i]), ".2f")
            line_90 = row['90%'][i]
            suc_rate = format((int(samples)-int(failures))/int(samples)*100, ".2f")
            if i < len(df)-1:
                pagesList.append((name,tps,avgtime,samples,failures,suc_rate,line_90,mintime,maxtime))
            else:
                summaryList=[samples, failures, suc_rate, avgtime, mintime, maxtime, tps]

        self.createHtml(pagesList, summaryList, self.outFile)

    def createHtml(self, pagesList, summaryList, filename=None):
        Htmltmp = r"""
    <!DOCTYPE html
      PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
       <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <title>Load test results</title><style type="text/css">
                                    body {
                                            font:normal 13px verdana,arial,helvetica;
                                            color:#000000;
                                    }
                                    table tr td, table tr th {
                                            font-size: 13px;
                                    }
                                    table.details tr th{
                                        color: #ffffff;
                                            font-weight: bold;
                                            text-align:center;
                                            background:#2674a6;
                                            white-space: nowrap;
                                    }
                                    table.details tr td{
                                            background:#eeeee0;
                                            white-space: nowrap;
                                    }
                                    h1 {
                                            margin: 0px 0px 5px; font: 18px verdana,arial,helvetica
                                    }
                                    h2 {
                                            margin-top: 1em; margin-bottom: 0.5em; font: bold 14px verdana,arial,helvetica
                                    }
                                    h3 {
                                            margin-bottom: 0.5em; font: bold 13px verdana,arial,helvetica
                                    }
                                    .Failure {
                                            font-weight:bold; color:red;
                                    }
       </style></head>
       <body>
          <h1>%s</h1>
          <hr size="1">
          <h2>Summary</h2>
          <table align="center" class="details" border="0" cellpadding="5" cellspacing="2" width="95%%">
             %s
          </table>
          <hr size="1" width="95%%" align="center">
          <h2>Pages</h2>
          <table align="center" class="details" border="0" cellpadding="5" cellspacing="2" width="95%%">
             %s
          </table>
          <hr size="1" width="95%%" align="center">
       </body>
    </html>
        """
        
        summary = '''            
             <tr valign="top">
                <th>Samples</th>
                <th>Failures</th>
                <th>Success Rate</th>
                <th>Average Time</th>
                <th>Min Time</th>
                <th>Max Time</th>
                <th>TPS</th>
             </tr>
             <tr valign="top" class="">
                <td align="center">%s</td>
                <td align="center">%s</td>
                <td align="center">%s%%</td>
                <td align="center">%s ms</td>
                <td align="center">%s ms</td>
                <td align="center">%s ms</td>
                <td align="center">%s</td>
             </tr>
                ''' % (summaryList[0],summaryList[1],summaryList[2],summaryList[3],summaryList[4],summaryList[5],summaryList[6])

        pages_list_table =""
        for idx in range(len(pagesList)):
                pages_list_table = pages_list_table + """<tr valign="top" class="">
                <td>%s</td>
                <td align="center">%s</td>
                <td align="center">%s ms</td>
                <td align="center">%s</td>
                <td align="center">%s</td>
                <td align="center">%s%%</td>
                <td align="center">%s ms</td>
                <td align="center">%s ms</td>
                <td align="center">%s ms</td>
             </tr>
            """ % (pagesList[idx][0],pagesList[idx][1],pagesList[idx][2],pagesList[idx][3],pagesList[idx][4],pagesList[idx][5],pagesList[idx][6],pagesList[idx][7],pagesList[idx][8])

        pages = """<tr valign="top">
                <th>URL</th>
                <th>QPS/TPS</th>
                <th>Average Time</th>
                <th>Samples</th>
                <th>Failures</th>
                <th>Success Rate</th>
                <th>90%%Line</th>
                <th>Min Time</th>
                <th>Max Time</th>
             </tr>
            %s\n""" % (pages_list_table)

        Htmlres = Htmltmp % (self.title, summary, pages)

        # Write html to a file
        addfile = open(filename, 'a', encoding='UTF-8')
        addfile.write(Htmlres)
        addfile.close()
        # print('File: ，', filename)
